package tt.dz.service.impl;

import java.io.Serializable;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tt.dz.common.Constants;
import tt.dz.dao.pro.UserFundCurrDao;
import tt.dz.dao.pro.UserMemberDao;
import tt.dz.dao.pro.UserRechargeBillDao;
import tt.dz.dao.pro.UserWalletDao;
import tt.dz.entity.UserFundCurr;
import tt.dz.entity.UserMember;
import tt.dz.entity.UserRechargeBill;
import tt.dz.entity.UserWallet;
import tt.dz.service.UserRechargeService;

/**
 * 用户充值业务实现
 * @author Administrator
 *
 */
@Service
public class UserRechargeServiceImpl implements UserRechargeService{

	/**用户充值操作Dao*/
	@Resource
	UserRechargeBillDao<UserRechargeBill> userRechargeBillDao;
	
	/**用户钱包dao*/
	@Resource
	UserWalletDao<UserWallet> userWalletDao;
	
	/**用户消费记录dao*/
	@Resource
	UserFundCurrDao<UserFundCurr> userFundCurrDao;
	
	/**会员Dao*/
	@Resource
	UserMemberDao<UserMember> userMemberDao;

	@Override
	public String userRecharge(UserRechargeBill userRechargeBill) {
		
		userRechargeBill.setRechange_result(0);
		userRechargeBill.setUpdate_time(new Date());
		Serializable serializable = userRechargeBillDao.save(userRechargeBill);
		if(serializable!=null){
			return Constants.JsonResponseCode.SUCCESS;
		}
		return Constants.JsonResponseCode.FAIL;
	}

	@Override
	public String finishRechargeBill(String alipayTradeNum,Integer userId) {
		
		UserRechargeBill userRechargeBill = userRechargeBillDao.findUserRechargeByRechargeIdAndUserId(alipayTradeNum,userId);
		if(userRechargeBill==null){
			return Constants.JsonResponseCode.ORDER_NOT_EXISTS;
		}
		//用户钱包
		UserWallet userWallet = userWalletDao.findUserWalletByUserId(userId);
		//用户信息
		UserMember userMember = userMemberDao.findUserMemberByUserId(userId);
		//修改余额
		userWallet.setBalance(userWallet.getBalance()+userRechargeBill.getPrice());
		userWalletDao.update(userWallet);
		
		//设置充值状态
		userRechargeBill.setRechange_result(1);
		userRechargeBill.setUpdate_time(new Date());
		userRechargeBillDao.update(userRechargeBill);
		
		/**充值记录*/
		UserFundCurr userFundCurr = new UserFundCurr();
		userFundCurr.setAlipay_trade_num(alipayTradeNum);
		//充值收入
		userFundCurr.setDeal_action(101);
		userFundCurr.setDeal_currt_num(userMember.getMobile()+(System.currentTimeMillis()+"").substring(0, 10));
		userFundCurr.setDeal_expend(0.00);
		userFundCurr.setDeal_income(userRechargeBill.getPrice());
		userFundCurr.setRemark("充值收入");
		userFundCurr.setUser_id(userId);
		userFundCurr.setUpdate_time(new Date());
		userFundCurr.setTrade_balance(userWallet.getBalance());
		userFundCurrDao.save(userFundCurr);
		return Constants.JsonResponseCode.SUCCESS;
	}
}
